<template>
  <div class="page-background">
    <div class="user-center-container">
      <a-card title="个人信息" :bordered="false" class="profile-card" :class="{ 'animate-in': showAnimation }">
        <a-form
          :model="formState"
          :rules="rules"
          ref="formRef"
          @finish="handleSubmit"
          layout="vertical"
        >
          <a-form-item label="用户 ID">
            <a-input :value="formState.id" readonly class="readonly-input">
              <template #suffix>
                <a-tooltip title="点击复制">
                  <CopyOutlined class="copy-icon" @click="copyUserId" />
                </a-tooltip>
              </template>
            </a-input>
          </a-form-item>

          <a-form-item label="头像" name="userAvatar">
            <a-upload
              v-model:file-list="fileList"
              :show-upload-list="false"
              :before-upload="beforeUpload"
              :customRequest="handleCustomUpload"
            >
              <div class="avatar-uploader">
                <img v-if="formState.userAvatar" :src="formState.userAvatar" alt="avatar" />
                <div v-else class="avatar-placeholder">
                  <UserOutlined />
                </div>
                <div class="avatar-hover-mask">
                  <CameraOutlined />
                  <span>更换头像</span>
                </div>
              </div>
            </a-upload>
          </a-form-item>

          <a-form-item label="用户名" name="userName">
            <a-input v-model:value="formState.userName" placeholder="请输入用户名" />
          </a-form-item>

          <a-form-item label="简介" name="userProfile">
            <a-textarea
              v-model:value="formState.userProfile"
              placeholder="请输入个人简介"
              :rows="4"
            />
          </a-form-item>

          <a-form-item class="form-actions">
            <a-button type="primary" html-type="submit" :loading="loading" size="large">
              保存修改
            </a-button>
          </a-form-item>
        </a-form>
      </a-card>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { UserOutlined, CopyOutlined, CameraOutlined } from '@ant-design/icons-vue';
import { useLoginUserStore } from '@/stores/useLoginUserStore';
import { updateUserUsingPost } from '@/api/userController';
import { uploadPictureUsingPost } from '@/api/pictureController.ts';
import { useRouter } from 'vue-router';

const router = useRouter();
const loginUserStore = useLoginUserStore();
const formRef = ref();
const loading = ref(false);
const fileList = ref([]);

// 控制动画是否显示
const showAnimation = ref(false); // 新增状态，用于触发进入动画

// 表单数据
const formState = reactive({
  id: '',
  userName: '',
  userProfile: '',
  userAvatar: '',
});

// 表单验证规则
const rules = {
  userName: [{ required: true, message: '请输入用户名' }],
};

/**
 * 复制用户ID到剪贴板
 */
const copyUserId = () => {
  if (navigator.clipboard) {
    navigator.clipboard.writeText(formState.id).then(() => {
      message.success('用户ID已复制到剪贴板');
    }).catch(err => {
      message.error('复制失败');
    });
  } else {
    message.warn('您的浏览器不支持自动复制功能');
  }
};

/**
 * 上传前校验文件类型和大小
 * @param file
 */
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    message.error('只能上传图片文件！');
  }
  const isLt4M = file.size / 1024 / 1024 < 4;
  if (!isLt4M) {
    message.error('图片大小不能超过 4MB！');
  }
  return isImage && isLt4M;
};

/**
 * 处理头像自定义上传
 * @param options
 */
const handleCustomUpload = async (options: any) => {
  const { file, onSuccess, onError } = options;
  try {
    const res = await uploadPictureUsingPost({ category: 'avatar' }, {}, file);

    if (res.data.code === 0 && res.data.data) {
      formState.userAvatar = res.data.data.url;
      onSuccess(res.data.data, file);
      message.success('头像上传成功');
    } else {
      onError(new Error(res.data.message || '上传失败'));
      message.error(res.data.message || '上传失败');
    }
  } catch (error) {
    onError(error);
    message.error('上传出现未知错误');
  }
};

/**
 * 提交表单处理用户更新
 * @param values
 */
const handleSubmit = async (values: any) => {
  loading.value = true;
  try {
    const res = await updateUserUsingPost({
      ...values,
      id: loginUserStore.loginUser.id,
      userAvatar: formState.userAvatar,
    });
    if (res.data.code === 0) {
      message.success('更新成功');
      // 更新本地用户信息
      loginUserStore.setLoginUser({
        ...loginUserStore.loginUser,
        ...values,
        userAvatar: formState.userAvatar,
      });
      // 导航回上一页或主页
      if (window.history.state.back) {
        router.back();
      } else {
        router.push('/');
      }
    } else {
      message.error('更新失败：' + res.data.message);
    }
  } catch (error) {
    message.error('更新失败');
  } finally {
    loading.value = false;
  }
};

// 组件挂载时初始化表单数据并触发进入动画
onMounted(() => {
  const user = loginUserStore.loginUser;
  formState.id = user.id || '';
  formState.userName = user.userName || '';
  formState.userProfile = user.userProfile || '';
  formState.userAvatar = user.userAvatar || '';

  // 在组件挂载后立即触发动画
  showAnimation.value = true;
});
</script>

<style scoped>
/*
 * 全局样式和动画定义
 */

/* 添加一个翻转进入的关键帧动画 */
@keyframes flipIn {
  0% {
    transform: rotateY(90deg) scale(0.8);
    opacity: 0;
    transform-origin: left center; /* 从左边开始翻转 */
  }
  50% {
    transform: rotateY(-10deg) scale(1.05); /* 稍微超过一点，增加动感 */
    opacity: 0.8;
  }
  100% {
    transform: rotateY(0deg) scale(1);
    opacity: 1;
    transform-origin: left center;
  }
}

/*
 * 动漫书拟态风格样式
 */

/* 页面整体背景 - 模拟旧书或纸张纹理 */
.page-background {
  background-color: #fcefdc; /* 浅米色/旧纸色 */
  background-image: url('data:image/svg+xml,%3Csvg width="6" height="6" viewBox="0 0 6 6" xmlns="http://www.w3.org/2000/svg"%3E%3Cg fill="%23d2c9b4" fill-opacity="0.4" fill-rule="evenodd"%3E%3Cpath d="M0 0h3v3H0V0zm3 3h3v3H3V3z"/%3E%3C/g%3E%3C/svg%3E'); /* 添加细微的纹理，模拟纸张 */
  min-height: calc(100vh - 48px); /* 减去通常的页头高度 */
  padding: 32px 0; /* 增加上下内边距 */
  perspective: 1000px; /* 开启3D透视，为翻转动画做准备 */
}

/* 内容容器 - 模拟一本打开的漫画书 */
.user-center-container {
  max-width: 900px; /* 稍微宽一点，像打开的书 */
  margin: 0 auto;
  padding: 0 24px;
  transform-style: preserve-3d; /* 确保子元素在3D空间中 */
  position: relative;
}

/* 信息卡片样式 - 模拟漫画中的“格子”或“弹出框” */
.profile-card {
  background-color: #ffffff; /* 卡片内部白色 */
  border-radius: 12px; /* 更圆润的边角 */
  box-shadow:
    8px 8px 15px rgba(0, 0, 0, 0.2), /* 较重的阴影，营造“弹出”感 */
    -4px -4px 10px rgba(255, 255, 255, 0.5); /* 顶部和左侧的亮光 */
  border: 3px solid #333; /* 粗描边，模拟漫画框 */
  position: relative;
  /* 初始的轻微3D旋转效果，为动画提供基础视觉 */
  transform: rotateY(-5deg) rotateX(2deg) translateZ(50px);
  transition: transform 0.5s ease; /* 鼠标悬停时的动画 */
}

/* 应用动画到卡片 */
.profile-card.animate-in {
  animation: flipIn 1.0s ease-out forwards; /* 动画持续1秒，缓出，并保持最后一帧状态 */
}

.profile-card:hover {
  transform: rotateY(0deg) rotateX(0deg) translateZ(0px); /* 鼠标悬停时稍微“回正” */
}

/* 卡片标题 - 漫画字体风格 */
:deep(.ant-card-head) {
  background-color: #ffd700; /* 鲜艳的标题背景，模拟漫画标题条 */
  color: #333;
  font-size: 22px;
  font-weight: 800; /* 更粗的字体 */
  text-align: center;
  border-bottom: 3px solid #333; /* 标题底部的描边 */
  border-top-left-radius: 9px;
  border-top-right-radius: 9px;
  letter-spacing: 1.5px; /* 增加字间距 */
  text-shadow: 1px 1px 0px rgba(255, 255, 255, 0.5), -1px -1px 0px rgba(0, 0, 0, 0.2); /* 浮雕效果 */
}

:deep(.ant-form-item) {
  margin-bottom: 28px; /* 增加表单项间距 */
}

/* 只读输入框 - 模拟文本框 */
.readonly-input {
  cursor: default;
  background-color: #f7f7f7;
  border: 1px solid #ccc; /* 细边框 */
  border-radius: 6px;
  padding: 8px 12px;
  box-shadow: inset 1px 1px 3px rgba(0, 0, 0, 0.1); /* 内部阴影 */
}

.copy-icon {
  cursor: pointer;
  color: #6a5acd; /* 紫色调，更具动漫感 */
  transition: color 0.3s;
}

.copy-icon:hover {
  color: #8a2be2;
}

/* 头像上传器 - 模拟圆形画框 */
.avatar-uploader {
  position: relative;
  width: 140px; /* 略大一点 */
  height: 140px;
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
  border: 4px solid #333; /* 粗描边 */
  box-shadow: 0 0 0 6px #fff, 0 0 0 8px #6a5acd; /* 外层白色光圈和紫色光晕 */
  transition: all 0.3s cubic-bezier(0.68, -0.55, 0.27, 1.55); /* 弹跳动画 */
  background-color: #eee;
  margin: 0 auto 20px; /* 居中显示 */
}

.avatar-uploader:hover {
  transform: scale(1.05); /* 悬停时轻微放大 */
  box-shadow: 0 0 0 6px #fff, 0 0 0 10px #8a2be2; /* 悬停时光晕扩大 */
}

.avatar-uploader img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 头像占位符 */
.avatar-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #dcdcdc; /* 更浅的背景 */
}

.avatar-placeholder :deep(.anticon) {
  font-size: 60px; /* 更大图标 */
  color: #666;
}

/* 头像悬浮遮罩 - 漫画风格提示 */
.avatar-hover-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(106, 90, 205, 0.7); /* 紫色半透明 */
  color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 16px; /* 字体大一点 */
  opacity: 0;
  transition: opacity 0.3s ease-in-out;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5); /* 字体阴影 */
}

.avatar-hover-mask .anticon {
  font-size: 32px; /* 图标大一点 */
  margin-bottom: 10px;
}

.avatar-uploader:hover .avatar-hover-mask {
  opacity: 1;
}

/* 输入框和文本域 - 简洁但有深度 */
:deep(.ant-input),
:deep(.ant-textarea) {
  border: 2px solid #ccc; /* 细边框 */
  border-radius: 8px;
  padding: 10px 15px;
  background-color: #fefefe;
  box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1); /* 柔和阴影 */
  transition: all 0.3s ease;
}

:deep(.ant-input:focus),
:deep(.ant-textarea:focus) {
  border-color: #6a5acd; /* 焦点时边框变色 */
  box-shadow: 2px 2px 8px rgba(106, 90, 205, 0.3); /* 焦点时阴影更明显 */
}

/* 表单操作按钮 - 漫画按钮风格 */
.form-actions {
  text-align: center; /* 按钮居中 */
  margin-top: 40px;
  margin-bottom: 0 !important; /* 最后一个元素不需要下边距 */
}

:deep(.ant-btn-primary) {
  background-color: #ff6347; /* 鲜艳的橙红色 */
  border: 3px solid #a83d2e; /* 描边 */
  border-radius: 10px;
  font-size: 20px; /* 大字体 */
  font-weight: bold;
  padding: 10px 30px; /* 增大按钮区域 */
  height: auto;
  box-shadow:
    5px 5px 10px rgba(0, 0, 0, 0.3), /* 强阴影 */
    inset 0 0 10px rgba(255, 255, 255, 0.5); /* 内部高光 */
  color: white;
  text-shadow: 2px 2px 0px rgba(0, 0, 0, 0.4); /* 文字阴影 */
  transition: all 0.2s cubic-bezier(0.175, 0.885, 0.32, 1.275); /* 弹跳动画 */
  transform: translateZ(0); /* 确保3D变换开启 */
  backface-visibility: hidden; /* 避免背面闪烁 */
}

:deep(.ant-btn-primary:hover) {
  background-color: #ff7f50; /* 悬停时颜色变浅 */
  transform: translateY(-3px) translateZ(10px); /* 向上浮动并向前 */
  box-shadow:
    7px 7px 15px rgba(0, 0, 0, 0.4),
    inset 0 0 15px rgba(255, 255, 255, 0.7);
}

:deep(.ant-btn-primary:active) {
  background-color: #c94c3a; /* 按下时颜色变深 */
  transform: translateY(0) translateZ(0); /* 按下时“沉入” */
  box-shadow:
    inset 2px 2px 5px rgba(0, 0, 0, 0.3),
    inset -2px -2px 5px rgba(255, 255, 255, 0.2);
}

/* 响应式布局 */
@media (max-width: 768px) {
  .user-center-container {
    padding: 0 16px;
  }
  .page-background {
    padding: 20px 0;
  }
  .profile-card {
    /* 移动端不进行初始的3D旋转，仅通过动画进入 */
    transform: none;
  }
}
</style>
